import json
import random

import requests
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_celery_beat.models import PeriodicTask, IntervalSchedule

from amap.tasks import download_file
from amap.utils import get_amap_data


class IpConfigView(View):
    """
        定位
    """

    def get(self, request):
        data = get_amap_data('https://restapi.amap.com/v3/ip', {
            'key': settings.AMAP_WEB_SERVICE_KEY,
            'ip': request.GET.get('ip', '')
        })

        return JsonResponse(data)


class GeoregeoView(View):
    """
        地理编码
    """

    def get(self, request):
        ip = request.GET.get('ip', '')
        req_url = f'https://restapi.amap.com/v3/geocode/geo?key={settings.AMAP_WEB_SERVICE_KEY}&ip={ip}'
        resp = requests.get(req_url)
        data = json.loads(resp.text)

        return JsonResponse(data)


class DistrictView(View):
    """
        行政区域查询
    """

    def get(self, request):
        data = get_amap_data('https://restapi.amap.com/v3/config/district', {
            'key': settings.AMAP_WEB_SERVICE_KEY,
            'keywords': request.GET.get('keywords', '')
        })

        return JsonResponse(data)


class DrivingView(View):
    """
        驾车路径规划:

            全局实时运行异步定时任务：
                1. 调用天气信息接口（6小时更新一下数据，同时扫描数据库受影响的路径，标记天气信息）
                2. 调用卫星信息接口（2小时更新一下数据，同时扫描数据库受影响的路径，标记卫星信息）

            创建行军任务：
                1. 创建任务：向数据库写入数据（对应的车队，任务状态，起始点和途径点）
                2. 创建异步定时任务：
                    a. 调用行军传感器接口（运行算法修改数据库数据）
                    b. 路径规划任务（基本只执行一次）
    """

    def get(self, request):
        data = get_amap_data('https://restapi.amap.com/v3/direction/driving', {
            'key': settings.AMAP_WEB_SERVICE_KEY,
            'extensions': request.GET.get('extensions', 'all'),
            'strategy': request.GET.get('strategy', 11),
            # 必要数据
            'origin': request.GET.get('origin', ''),
            'destination': request.GET.get('destination', ''),
            'waypoints': request.GET.get('waypoints', ''),
        })

        CAR_WEIGHT = '12'
        CAR_WIDTH = '4'
        CAR_ANGURL = '3'

        paths = data['route']['paths']
        for path in paths:
            cnt = random.randint(0, 5)
            for item in path['steps']:
                item['type'] = 'normal'
            for _ in range(cnt):
                item = random.choice(path['steps'])
                item['type'] = 'danger'

            # todo 通行性判别
            # 判断 转弯半径、车重、车宽

        return JsonResponse(data)


class TestCeleryBeatView(View):
    def get(self, request):
        # 创建定时策略
        schedule, created = IntervalSchedule.objects.get_or_create(every=10, period=IntervalSchedule)

        # 创建任务
        task = PeriodicTask.objects.create(interval=schedule, name='say welcome',
                                           task='nav_geng_api.say_welcome', args=[])

        return JsonResponse({'status': 0})


class TestCeleryView(View):
    def get(self, request):
        download_file.delay()
        return JsonResponse({'status': 0})
